package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.itheima.dao.OrderSettingDao;

import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> data) {
        //判断是否为空
        if(data != null && data.size() >0){

            //判断是否日期重复，重复更新，不重复添加
            for (OrderSetting datum : data) {
                //通过日期查询数据库中是否有数据
                long count = orderSettingDao.findCountByOrderDate(datum.getOrderDate());

                if(count > 0){
                    //说明已经存在进行更新
                    orderSettingDao.editNumberByOrderDate(datum);
                }else{
                    //不存在进行添加
                    orderSettingDao.add(datum);
                }

            }

        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {

        String start = date + "-1";
        String end = date + "-31";

        Map<String,String> map = new HashMap<>();
        map.put("start",start);
        map.put("end",end);

        List<OrderSetting> orderSettings = orderSettingDao.getOrderSettingByMonth(map);

        List<Map> list = new ArrayList<>();
        if(orderSettings.size()>0 && orderSettings != null){

            for (OrderSetting orderSetting : orderSettings) {
                Map m = new HashMap();
                //获取天数
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(orderSetting.getOrderDate());
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                m.put("date",day);
                m.put("number",orderSetting.getNumber());
                m.put("reservations",orderSetting.getReservations());
                list.add(m);
            }
        }
        return list;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //查询当前日期是否存在，有进行修改，。没有添加
        Date orderDate = orderSetting.getOrderDate();
        long count = orderSettingDao.findCountByOrderDate(orderDate);
        if(count > 0){
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            orderSettingDao.add(orderSetting);
        }
    }

    @Override
    public void delOrderSettingByDate(String date) {

        orderSettingDao.delOrderSettingByDate(date);
    }
}
